package com.fileUpload.utilities;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

public class UploadUtil
{
    public static final String TYPERAR = "rar";
    public static final String TYPEZIP = "zip";
    public static String saveNewNameFile(String filePath)
    {
        Date dt = new Date();
        long lg = dt.getTime();
        Long ld = new Long(lg);

        String newName = ld.toString();

        int beginIndex = filePath.lastIndexOf("\\") + 1;
        int endIndex = filePath.lastIndexOf(".");
        String subStr = filePath.substring(beginIndex, endIndex);
        String newFilePath = filePath.replaceAll(subStr, newName);

        return newFilePath;
    }

    // 截取文件名
    public static String subFileName(String newFilePath)
    {
        int a = newFilePath.lastIndexOf("\\") + 1;
        int b = newFilePath.length();
        return newFilePath.substring(a, b);
    }

    // 文件类型�
    public static String subFileType(String newFilePath)
    {
        int a = newFilePath.lastIndexOf(".") + 1;
        int b = newFilePath.length();
        return newFilePath.substring(a, b);
    }

    // ԭ原文件名�ļ���
    public static String subOldFileName(String newFilePath)
    {
        int beginIndex = newFilePath.lastIndexOf("\\") + 1;
        int endIndex = newFilePath.lastIndexOf(".");
        return newFilePath.substring(beginIndex, endIndex);
    }

    // 替换文件名���
    public static String replaceFileName(String fileName, String newFileName)
    {
        int index = fileName.lastIndexOf(".");
        String oldFileName = fileName.substring(0, index);
        return fileName.replace(oldFileName, newFileName);
    }

    public static boolean saveFile(InputStream is, String filePath)
    {
        boolean saveOk = false;
        try
        {
            File f = new File(filePath);
            InputStream inputStream = is;
            OutputStream out = new FileOutputStream(f);
            byte buf[] = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0)
            {
                out.write(buf, 0, len);
            }
            out.close();
            inputStream.close();
            saveOk = true;
        }
        catch (IOException e)
        {
            //
        }
        return saveOk;
    }

    public static boolean checkTypes(String[] types, String[] targettype)
    {
        boolean bool = false;
        for (int i = 0; i < types.length; i++)
        {
            if (types[i].equalsIgnoreCase(targettype[targettype.length - 1]))
            {
                bool = true;
                break;
            }
        }
        return bool;
    }
    
    
}
